import { createRouter, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
//配置路由加载效果
NProgress.inc(2);
NProgress.configure({ easing: 'ease', speed: 500, showSpinner: false }); // 动作

const Layout = () => import('../views/Layout.vue')
const Home = () => import('../views/Home.vue')
const User = () => import('../views/user/Index.vue')
const Role = () => import('../views/role/Index.vue')
const EditRole = () => import('../views/role/Form.vue')
const Login = () => import('../views/login/Index.vue')
const Chat = () => import('../views/chat/Index.vue')
const Menus = () => import('../views/menu/Index.vue')

const logined = false

const requiredAuth = (to, from, next) => {
  if (logined) {
    return next(true)
  } else {
    return next("/login")
  }
}

const routes = [
  {
    path: '/',
    name: '/',
    component: Layout,
    children: [
      {
        path: '/home',
        name: 'home',
        component: Home,
        meta: {
          title: '首页'
        },
      },
      {
        path: '/chat',
        name: 'chat',
        component: Chat,
        meta: {
          title: '会话'
        },
      },
      {
        path: '/users',
        name: 'users',
        component: User,
        meta: {
          title: '用户管理'
        },
      },
      {
        path: '/roles',
        name: 'roles',
        component: Role,
        meta: {
          title: '角色管理'
        },
      },
      {
        path: '/role/edit:id?',
        name: 'role.edit',
        component: EditRole,
        meta: {
          title: '角色管理'
        },
      },
      {
        path: '/menus',
        name: 'menus',
        component: Menus,
        meta: {
          title: '菜单管理'
        },
      },
    ]
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      title: '请登录'
    },
    component: Login
  },
]


const router = new createRouter({
  history: createWebHashHistory(), // hash模式：createWebHashHistory，history模式：createWebHistory
  routes
})

// 导航跳转开始
router.beforeEach((to, from, next) => {
  //路由加载效果开始
  NProgress.start()

  if (to.meta.title) {
    document.title = to.meta.title
  }

  const userToken = window.sessionStorage.getItem('token')
  if (userToken) {
    //已经登录过，但是访问的是login，强制跳转至首页
    if (to.path == '/login') {
      return next('/home')
    } else {
      return next(true)
    }
  } else {
    if (to.path !== '/login') {
      return next('/login')
    } else {
      return next(true)
    }
  }
})

router.afterEach((to, from, next) => {
  //路由加载效果结束
  NProgress.done()
})



export default router